import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:dear_lottery/Home/views/DL_headerView_homePage.dart';
import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import '../EJ_webview/EM_WebViewPage.dart';
import '../tools/MMPermissionHelper.dart';
import 'drawer/DL_ContactusVC.dart';
import 'views/DL_generator_homePage.dart';
import 'views/DL_resultView_homePage.dart';
import 'views/DL_staticsEnter_homePage.dart';
// import '../tools/KaL_Config.dart';

class DlHomepageVC extends StatefulWidget {
  DlHomepageVC({super.key, this.pageController});
  PageController? pageController;
  @override
  State<DlHomepageVC> createState() => _DlHomepageVCState();
}

class _DlHomepageVCState extends State<DlHomepageVC> {
  //
  late ScrollController _controller = ScrollController();

  int _tabIndex = 0; //0:1pm,1:6pm,2:8pm,3:others

  String _authStatus = 'Unknown';
  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlugin() async {
    final TrackingStatus status =
        await AppTrackingTransparency.trackingAuthorizationStatus;
    setState(() => _authStatus = '$status');
    // If the system can show an authorization request dialog
    if (status == TrackingStatus.notDetermined) {
      // Show a custom explainer dialog before the system dialog
      await showCustomTrackingDialog(context);
      // Wait for dialog popping animation
      await Future.delayed(const Duration(milliseconds: 200));
      // Request system's tracking authorization dialog
      final TrackingStatus status =
          await AppTrackingTransparency.requestTrackingAuthorization();
      setState(() => _authStatus = '$status');
    }

    ///获取到uuid
    final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
    debugPrint("UUID: $uuid");
  }

  Future<void> showCustomTrackingDialog(BuildContext context) async =>
      await showDialog<void>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('Dear User'),
          content: const Text(
            'We care about your privacy and data security. We keep this app free by showing ads. '
            'Can we continue to use your data to tailor ads for you?\n\nYou can change your choice anytime in the app settings. '
            'Our partners will collect data and use a unique identifier on your device to show you ads.',
          ),
          actions: [
            TextButton(
              // onPressed: () => Navigator.pop(context),
              onPressed: () {
                hidenCustomTrackingDialog(context);
              },
              child: const Text('Continue'),
            ),
          ],
        ),
      );

  void hidenCustomTrackingDialog(BuildContext context) {
    Navigator.pop(context);
  }

  MM_configPermission() async {
    debugPrint('++++++获取推送权限');
    MMPermissionHelper().check(
      [
        Permission.notification,
        // Permission.appTrackingTransparency
      ],
      onSuccess: () {
        debugPrint('notification-onSuccess');
        setState(() {});
      },
      onFailed: () {
        debugPrint('notification-onFailed');
        setState(() {});
      },
      onOpenSetting: () {
        debugPrint('-notification-onOpenSetting');
      },
    );
  }

  void DL_readPolicy() {
    debugPrint('NL_readPolicy');
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const EJWebViewPage(
              url: DL_Config.DL_policy,
              haveAppBar: true,
              title: 'Privacy Policy')),
    );
  }

  void DL_readTerms() {
    debugPrint('NL_readTerms');
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const EJWebViewPage(
                url: DL_Config.DL_terms,
                haveAppBar: true,
                title: 'Terms & Conditions',
              )),
    );
  }

  void DL_goContactUS() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const DlContactusvc()),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    MM_configPermission();

    ///请求跟踪权限
    WidgetsFlutterBinding.ensureInitialized()
        .addPostFrameCallback((_) => initPlugin());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: DL_Config.DL_pageBgColor,
      endDrawer: RightDrawer(
        onTap: (p0) {
          debugPrint('$p0');
          switch (p0) {
            case 0:
              DL_readPolicy();
            case 1:
              DL_readTerms();
            case 2:
              DL_goContactUS();

              break;
            default:
          }
        },
      ), // 设置右侧抽屉
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: DL_Config.DL_navgatBarColor,
        foregroundColor: DL_Config.DL_navgatBarTitleColor,
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        actions: [
          Builder(
            //解决点击按钮没反应
            builder: (BuildContext context) {
              return IconButton(
                icon: const Icon(Icons.menu),
                onPressed: () {
                  // 打开右侧抽屉
                  Scaffold.of(context).openEndDrawer();
                },
              );
            },
          ),
        ],
      ),

      body: ListView(
        controller: _controller,
        children: [
          DL_headerview_home(),
          DL_resultView_homePage(
            pageController: widget.pageController,
            onTabChanged: (tabIndex) {
              // setState(() {
              //   _tabIndex = tabIndex;
              // });
            },
          ),
          DL_staticsEnter_home(
            pageController: widget.pageController,
          ),
          DL_generator_home(
            pageController: widget.pageController,
          ),
        ],
      ),
    );
  }
}

class RightDrawer extends StatelessWidget {
  //回传点击事件
  final Function(int) onTap;
  RightDrawer({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Container(
        color: DL_Config.DL_MainColor,
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                color: DL_Config.DL_MainColor,
              ),
              child: Center(
                child: Container(
                  decoration: const BoxDecoration(
                      // color: Colors.yellow,
                      borderRadius: BorderRadius.all(Radius.circular(8))),
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(8), //
                      child: Image.asset(
                        'assets/sys_imgs/DearLottery Logo.png',
                        width: 180,
                        height: 124,
                      )),
                ),
              ),
            ),
            listTile(context, 'Privacy Policy', 0),
            listTile(context, 'Terms & Conditions', 1),
            listTile(context, 'Contact us', 2),
          ],
        ),
      ),
    );
  }

  Widget listTile(
    BuildContext context,
    String title,
    int index,
  ) {
    return ListTile(
      trailing: const Icon(
        Icons.arrow_right_outlined,
        color: Colors.white, // 自定义颜色
        size: 24.0, // 自定义大小
      ),
      title: Text(
        title,
        style:
            const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
      ),
      onTap: () {
        // 处理点击事件
        Navigator.pop(context); // 关闭抽屉
        onTap(index);
      },
    );
  }
}
